import router from "@/routers/index";
import { message } from "ant-design-vue";
import Axios, {
  type AxiosError,
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
} from "axios";

type ExtendAxiosResponse = AxiosResponse & {
  config: {
    _retry?: boolean;
  };
};
// 默认 axios 实例请求配置
const configDefault = {
  timeout: 60000,
  // baseURL: '',
  baseURL: import.meta.env.VITE_API_URL,
  data: {},
  headers: {
    "Content-Encoding": "utf-8",
  },
};

class Http {
  // 当前实例
  private static axiosInstance: AxiosInstance;
  // 请求配置
  private static axiosConfigDefault: AxiosRequestConfig;

  // 请求拦截
  private httpInterceptorsRequest(): void {
    Http.axiosInstance.interceptors.request.use(
      (config) => {
        return config;
      },
      (error: AxiosError) => {
        message.error(error.message);
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截
  private httpInterceptorsResponse(): void {
    Http.axiosInstance.interceptors.response.use(
      async (response: ExtendAxiosResponse) => {
        // 与后端协定的返回字段

        if (response.data?.statusCode && response.data?.statusCode !== 200) {
          message.error(response.data?.errors || "请求失败");
          return Promise.reject(new Error("请求失败"));
        }
        // 判断请求是否成功
        return response.data;
      },
      (error: any) => {
        if (error.status === 401) {
          message.error("请重新登录");
          localStorage.clear();
          router.replace("/login");
        }
        return Promise.reject(error);
      }
    );
  }

  constructor(config: AxiosRequestConfig) {
    Http.axiosConfigDefault = config;
    Http.axiosInstance = Axios.create(config);
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  // 通用请求函数
  public request<T>(
    paramConfig: AxiosRequestConfig & { showError?: boolean }
  ): Promise<T> {
    const token = localStorage.getItem("token");
    const config = {
      ...Http.axiosConfigDefault,
      showError: true,
     withCredentials:false,
      ...paramConfig,
      headers: {
        Authorization: `Bearer ${token}`,
      },
    };
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response.data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
}

export const http = new Http(configDefault);
